package com.bjtu.transactionclient.service;

import com.bjtu.transactionclient.api.api.JournalPaperService;
import com.bjtu.transactionclient.api.constant.Constans;
import com.bjtu.transactionclient.api.utils.StringSimilarityUtil;
import com.bjtu.transactionclient.api.vo.request.SyncJournalPaperRequest;
import com.bjtu.transactionclient.base.result.FailEnum;
import com.bjtu.transactionclient.base.result.Result;
import com.bjtu.transactionclient.base.result.SuccessEnum;
import com.bjtu.transactionclient.dao.AuthorIndexDao;
import com.bjtu.transactionclient.dao.JournalPaperCnDao;
import com.bjtu.transactionclient.dao.JournalPaperEnDao;
import com.bjtu.transactionclient.dao.UserIndexDao;
import com.bjtu.transactionclient.domain.AuthorIndex;
import com.bjtu.transactionclient.domain.JournalPaperChinese;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author caiyuli
 * @date 2020/4/23 11:45 上午
 */

@Service
public class JournalPaperServiceImpl implements JournalPaperService {

    @Autowired
    private JournalPaperCnDao journalPaperCnDao;

    @Autowired
    private JournalPaperEnDao journalPaperEnDao;

    @Autowired
    private AuthorIndexDao authorIndexDao;

    @Autowired
    private UserIndexDao userIndexDao;

    @Override
    public List<JournalPaperChinese> getAllJournalPaperChinese() {
        return journalPaperCnDao.queryAllJournalPaperChinese();
    }

    @Override
    public Result syncJournalPaper(SyncJournalPaperRequest request) {

        Result result = null;
        String indexCode = request.getUserIndexNo().getIndexCode();
        if (indexCode.equals(Constans.IndexCode.JOURNAL_PAPER_EN)){
            // 英文期刊析出
            result =  handleJournalEnPaper(request);
        } else if (indexCode.equals(Constans.IndexCode.JOURNAL_PAPER_CN)){
            // 中文期刊析出
            result =  handleJournalCnPaper(request);
        }

        if (result == null){
            return Result.fail("不能处理该期刊析出类型");
        }

        return result;
    }


    private Result handleJournalCnPaper(SyncJournalPaperRequest request){
        Result result = null;

        JournalPaperChinese journalChinese = journalPaperCnDao.queryByIndexNo(request.getUserIndexNo().getIndexNo());
        if ( null == journalChinese){
            // 没有索引号冲突  需要做一个全量的数据匹配

            List<JournalPaperChinese> journalChineseList = journalPaperCnDao.queryByJournalIndexNo(request.getJournalPaperChinese().getJournalIndexNo());
            if (journalChineseList.size() == 0){
                //  没有相同期刊索引号的数据  直接插入
                insertJournalPaperCn(request);
                return Result.success(null,SuccessEnum.JOURNAL_PAPER_NEW);
            }

            for (int i = 0; i < journalChineseList.size(); i++){
                if (isSame(request.getJournalPaperChinese(),journalChineseList.get(i))){
                   return Result.success(journalChineseList.get(0).getIndexNo(), SuccessEnum.JOURNAL_PAPER_INDEX_NOT_SAME_BUT_NATURE_SAME);
                }
            }
            insertJournalPaperCn(request);
            return Result.success(null,SuccessEnum.JOURNAL_PAPER_NEW);

        }else {
            //有索引号相同  判断时候为统一文章
            if (isSame(journalChinese, request.getJournalPaperChinese())){
                // 相同文章
                return Result.success(null, SuccessEnum.JOURNAL_PAPER_SAME_AND_NATURE_DIFFERENT);
            }else {
                //不同文章
                String prefix = request.getAuthorIndex().getIndexNo().substring(0,request.getAuthorIndex().getIndexNo().length()-1) + '%';
                List<String> indexNoList =  userIndexDao.queryUserIndexNoLike(prefix);
                char lastLetter = LastIndexCodeLetter(indexNoList);

                if (lastLetter == 'A' && indexNoList.size() > 0){
                    //没有索引号分配了
                    return Result.fail(null, FailEnum.INDEXNO_FULL);
                }
                result = Result.success(lastLetter,SuccessEnum.JOURNAL_PAPER_INDEX_REDISTRIBUTION);
            }
        }
        return result;
    }

    private Result handleJournalEnPaper(SyncJournalPaperRequest request){
        //TODO : 英文和和中文的一样
        return null;
    }

    private Boolean isSame(JournalPaperChinese journalPaperChinese1, JournalPaperChinese journalPaperChinese2){
        // 统一期刊
        if (!journalPaperChinese1.getJournalIndexNo().equals(journalPaperChinese2.getJournalIndexNo())){
            return false;
        }
        AuthorIndex firstAuthor1 = authorIndexDao.queryFirstAuthorByIndexNo(journalPaperChinese1.getIndexNo());
        AuthorIndex firstAuthor2 = authorIndexDao.queryFirstAuthorByIndexNo(journalPaperChinese2.getIndexNo());

        // 作者
        if (!isSameAuthor(firstAuthor1,firstAuthor2)){
            return false;
        }

        if (StringSimilarityUtil.cos(journalPaperChinese1.getTitle2(),journalPaperChinese2.getTitle2()) < Constans.SIMILARITY_THRESHOLD){
            return false;
        }
        return true;
    }

    private Boolean isSameAuthor( AuthorIndex firstAuthor1, AuthorIndex firstAuthor2){
        if (firstAuthor1 == null && firstAuthor2 == null){
            return true;
        }
        if (firstAuthor1 == null && firstAuthor2 != null){
            return false;
        }
        if (firstAuthor1 != null && firstAuthor2 == null){
            return false;
        }
        String lastName1 = firstAuthor1.getLastName().trim().toLowerCase();
        String lastName2 = firstAuthor2.getLastName().trim().toLowerCase();
        if (!lastName1.equals(lastName2)){
            return false;
        }

        if (!StringUtils.isBlank(firstAuthor1.getFirstName()) && !StringUtils.isBlank(firstAuthor2.getFirstName())) {
            String firstName1 = firstAuthor1.getFirstName().trim().toLowerCase();
            String firstName2 = firstAuthor2.getFirstName().trim().toLowerCase();
            if (! firstName1.equals(firstName2)){
                return false;
            }
        }
        if (!StringUtils.isBlank(firstAuthor1.getFirstName())  && StringUtils.isBlank(firstAuthor2.getFirstName())){
            return false;
        }

        if (StringUtils.isBlank(firstAuthor1.getFirstName())  && !StringUtils.isBlank(firstAuthor2.getFirstName())){
            return false;
        }

        if (!StringUtils.isBlank(firstAuthor1.getMiddleName())  && StringUtils.isBlank(firstAuthor2.getMiddleName())){
            return false;
        }

        if (StringUtils.isBlank(firstAuthor1.getMiddleName())  && !StringUtils.isBlank(firstAuthor2.getMiddleName())){
            return false;
        }
        if (!StringUtils.isBlank(firstAuthor1.getMiddleName()) && !StringUtils.isBlank(firstAuthor2.getMiddleName())) {
            String middleName1 = firstAuthor1.getMiddleName().trim().toLowerCase();
            String middleName2 = firstAuthor2.getMiddleName().trim().toLowerCase();
            if (! middleName1.equals(middleName1)){
                return false;
            }
        }
        return true;
    }

    /**
     * 返回索引号下一个字母
     * @param indexNoList
     * @return
     */
    private Character LastIndexCodeLetter(List<String> indexNoList){
        char result = 'A';
        for (int i = 0; i < indexNoList.size(); i++){
            String str = indexNoList.get(i);
            char t = str.charAt(str.length()-1);
            if (t > result){
                result = t;
            }
        }
        if (result < 'Z'){
            return (char)(result+1);
        }
        return result;
    }

    private void insertJournalPaperCn(SyncJournalPaperRequest request){
        userIndexDao.addUserIndexNoTable(request.getUserIndexNo());
        authorIndexDao.add(request.getAuthorIndex());
        journalPaperCnDao.add(request.getJournalPaperChinese());
    }


}
